package com.example.heizhu.appfuncore.deeplinkdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

import com.example.heizhu.appfuncore.R;

import java.util.List;

import core.android.deeplinks.deeplinking.AKDeeplink;
import core.android.deeplinks.deeplinking.annotations.DeeplinkFragmentActivity;
import core.android.tools.AK;
import core.app.fragment.CategoryFragment;
import core.app.fragment.HotFragment;
import core.app.fragment.IndexFragment;
import core.app.fragment.MineFragment;
import core.app.fragment.NeiborFragment;

@DeeplinkFragmentActivity(id = R.id.frame_layout, fragments = {
        Html5Fragment.class,
        IndexFragment.class,
        HotFragment.class,
        NeiborFragment.class,
        CategoryFragment.class,
        MineFragment.class})
public class AppFragmentActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        AK.d(getIntent().getExtras());
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_fragment);
        AKDeeplink.INSTANCE.inject(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        AK.d(intent);
        super.onNewIntent(intent);
        AKDeeplink.INSTANCE.injectOnNewIntent(this, intent);
    }

    @Override
    protected void onDestroy() {
        AK.d();
        super.onDestroy();
    }
    @Override
    public void onBackPressed() {
        Fragment visibleFragment = getVisibleFragment();
        AK.d("visibleFragment=" + visibleFragment);
        if (visibleFragment == null) {
            super.onBackPressed();
        } else {
            visibleFragment.onOptionsItemSelected(null);
        }
    }

    //当前显示的fragment 只适用于v4包
    public Fragment getVisibleFragment() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        AK.d(fragments);
        if (fragments != null) {
            for (int i = fragments.size() - 1; i >= 0; i--) {
                Fragment fragment = fragments.get(i);
                if (fragment != null && fragment.isVisible())
                    return fragment;
            }
        }
        return null;
    }
}
